/**
 * Copyright(c) by JNet Smartware Group.
 * All rights reserved. Not distribution or redistribution without
 * any permission of JNet Smartware Group.
 * 
 * @author thuc
 * 2010/07/31
 */
package vn.smartware.co.server.action;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import vn.smartware.co.commons.Const;
import vn.smartware.co.forms.RegisterCustomerForm;
import vn.smartware.co.framework.action.BaseAction;
import vn.smartware.co.framework.bean.LoginDTO;
import vn.smartware.co.framework.bean.AddressDTO;
import vn.smartware.co.framework.config.SystemConfig;
import vn.smartware.co.framework.exception.ServerException;
import vn.smartware.co.framework.form.ActionForm;
import vn.smartware.co.server.dao.factory.AbstractInitializeDAO;
import vn.smartware.co.server.dao.factory.AbstractRegisterCustomerDAO;
import vn.smartware.co.server.dao.factory.DaoFactory;

/**
 * RegisterRoomAction
 * @author thuctt
 */
public class RegisterCustomerAction extends BaseAction {

	private static Log log = LogFactory.getLog(RegisterCustomerAction.class);
	
	/**
	 * register room list
	 * @param request
	 * @param response
	 * @param config
	 * @param aForm
	 * @return ActionForm
	 * @throws ServerException
	 */
	public ActionForm saveAction(HttpServletRequest request,
			HttpServletResponse response, SystemConfig config, ActionForm aForm)
			throws ServerException {

		RegisterCustomerForm form = (RegisterCustomerForm)aForm;
		AddressDTO addr = form.getCustomer().getAddress();
		LoginDTO user = (LoginDTO)form.getUserDTO();
		AbstractRegisterCustomerDAO dao = DaoFactory.createRegisterCustomerDAO();
		AbstractInitializeDAO initdao = DaoFactory.createInitializeDAO();
		Connection conn = getConnection();
		
		try {
			if (form.getProcessMode().equals(Const.MODE_NEW)) {
				initdao.insertAddress(addr, user, conn);
				addr.setAddressCd(initdao.getMaxAddressCd(addr, user, conn));
				form.setCustomerNo(dao.registerCustomer(form.getCustomer(), user, conn));
				
			} else if (form.getProcessMode().equals(Const.MODE_EDIT)) {
				dao.updateCustomer(form.getCustomer(), user, conn);
				initdao.updateAddress(addr, user, conn);
				
			} else if (form.getProcessMode().equals(Const.MODE_DEL)) {
				dao.deleteCustomer(form.getCustomer(), user, conn);
				initdao.deleteAddress(addr, conn);
			}
			
			commit(conn);
			
		} catch (ServerException e) {
			log.error("ServerException.", e);
			rollback(conn);
			throw e;
		} finally {
			closeConnection(conn);
		}
		return form;
	}
	
}
